import { defineStore } from 'pinia'
import { login as reqLogin } from '@/api/user'
import { LoginForm } from '@/api/user/type'
import { localStorage } from '@/utils/localStorage'
import { Enums } from '@/utils/sysVar'
import { UserState } from '@/store/modules/types'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: localStorage.get(Enums.TOKEN),
    }
  },
  actions: {
    login(loginFormData: LoginForm) {
      return reqLogin(loginFormData)
        .then((res) => {
          if (res.code !== 1) return Promise.resolve(res)

          // 保存 token 到两处缓存
          this.token = 'fake token'
          localStorage.set(Enums.TOKEN, this.token)

          return Promise.resolve(res)
        })
        .catch((err) => {
          return Promise.reject(err)
        })
    },
  },
  getters: {},
})

export default useUserStore
